﻿using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading.Tasks;
using Topro.Application.Interface;
using Topro.Entity;
using Topro.Entity.Enum;
using Topro.Entity.Request.InventoryItem;
using Topro.Entity.Request.StockIn;

namespace Topro.Web.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [EnableCors("Policy")]
    public class WCSController : ControllerBase
    {
        #region 注入
        /// <summary>
        /// 日志接口
        /// </summary>
        private readonly LogService _logService;

        /// <summary>
        /// 入库接口
        /// </summary>
        private readonly StockInService _stockInService;

        /// <summary>
        /// 库存接口
        /// </summary>
        private readonly ASRSJOBService _ASRSJOBService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logService">日志接口</param>
        /// <param name="stockInService">入库接口</param>
        public WCSController(LogService logService,  StockInService stockInService, ASRSJOBService ASRSJOBService)
        {
            _logService = logService;
            _stockInService = stockInService;
            _ASRSJOBService = ASRSJOBService;
        }
        #endregion

        #region 测试
        /// <summary>
        /// 测试
        /// </summary>
        /// <returns></returns>
        public IActionResult Info()
        {
            return Content("Info");
        }
        #endregion

        #region 空托入库
        /// <summary>
        /// 空托入库
        /// </summary>
        /// <returns></returns>
        public IActionResult StockIn(StockInSaveRequest stockIn)
        {
            try
            {
                //http://localhost:5000/api/wcs/StockIn
                //明细
                var inventoryItems = new List<InventoryItemSaveRequest>();
                //{
                //"ContainerCode":1001,
                //"StationNo":3
                //}
                //单据编号
                stockIn.OrderId = $"RK{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                //托盘编码
                if (!stockIn.ContainerCode.HasValue)
                {
                    throw new Exception("请输入托盘编码.");
                }
                //站台
                if (!stockIn.StationNo.HasValue)
                {
                    throw new Exception("请选择入库站台.");
                }

                var containerCode = stockIn.ContainerCode.Value.ToString();

                var ASRSJOB = _ASRSJOBService.GetByContainerCode(containerCode);
                if (ASRSJOB != null)
                {
                    return new Response<string>()
                    {
                        Success = true,
                        Message = "实托编码已存在,等待垛机执行",
                        Data = ""
                    };
                }
                else
                {
                    //标记空托入库
                    stockIn.IsContainer = (int)IsContainer.空;
                    //创建人
                    stockIn.CreatedBy = 1;

                    var response = _stockInService.Save(stockIn, inventoryItems);

                    return new Response<string>()
                    {
                        Success = response.Success,
                        Message = "创建空托入库指令成功.",
                        Data = ""
                    };
                }
            }
            catch (Exception ex)
            {
                return new Response<string>()
                {
                    Success = false,
                    Message = ex.Message,
                    Data = ""
                };
            }
        }
        #endregion
    }

    #region 
    /// <summary>
    /// 输出
    /// </summary>
    public class Response<T> : IActionResult
    {
        /// <summary>
        /// 状态
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 状态代码
        /// </summary>
        public int StatusCode { get; set; }

        /// <summary>
        /// 返回信息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 数据
        /// </summary>
        public T Data { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task ExecuteResultAsync(ActionContext context)
        {
            return Task.Run(() =>
            {
                var response = context.HttpContext.Response;
                response.ContentType = "application/json; charset=utf-8";
                var jsonSerializerSettings = new JsonSerializerSettings
                {
                    Converters = new List<JsonConverter>
                    {
                        new DateTimeJsonConverter(),
                    }
                };
                var json = JsonConvert.SerializeObject(this, jsonSerializerSettings);
                var bytes = Encoding.UTF8.GetBytes(json);
                context.HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
            });
        }
    }

    /// <summary>
    /// JSON时间转换
    /// </summary>
    public class DateTimeJsonConverter : JsonConverter
    {
        private const string CustomFormat = "yyyy-MM-dd HH:mm:ss";

        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(DateTime) || objectType == typeof(DateTime?));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null)
            {
                return null;
            }

            var s = reader.Value.ToString();

            if (DateTime.TryParseExact(s, CustomFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var result))
            {
                return result;
            }

            return null;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(((DateTime)value).ToString(CustomFormat));
        }
    }
    #endregion
}
